/*
 * Functional.java
 * business
 *
 * Created by SunDing on 2016/9/9.
 *
 * Copyright (c) 2016年 yidiandao. All rights reserved.
 */

package com.yidiandao.business.ui.widget.listview;

import java.util.ArrayList;
import java.util.List;

/**
 * 服务端与客户端数据的转换,可在Response中调用
 */
public class Functional {

    /**
     * 对List类型进行转换,将服务端的List转换成客户端List( 1Server 对 1Client )
     *
     * @param sources   服务端List
     * @param processor 转换接口
     * @param <From>    服务端Bean的泛型
     * @param <To>      客户端Bean的泛型
     * @return 客户端Bean的集合
     */
    public static <From, To> List<To> serverToClient(List<From> sources, Processor<From, To> processor) {
        List<To> list = new ArrayList<>();

        // 对服务端的数据进行遍历
        for (From from : sources) {
            // 将服务端的数据转换成客户端类型
            To client = processor.processToClient(from);
            if (client != null) {
                list.add(client);
            }
        }

        return list;
    }

    /**
     * 对List类型进行转换,将服务端的List转换成客户端List( 1 Server 对 多Client )
     *
     * @param sources        服务端List
     * @param multiProcessor 转换接口
     * @param <From>         服务端Bean的泛型
     * @param <To>           客户端Bean的泛型
     * @return 客户端Bean的集合
     */
    public static <From, To> List<To> serverToClient(List<From> sources, MultiProcessor multiProcessor) {
        List<To> list = new ArrayList<>();

        for (From source : sources) {
            List<To> clients = multiProcessor.processToClient(source);
            if (clients != null && clients.size() != 0) {
                list.addAll(clients);
            }
        }

        return list;
    }

    public interface Processor<From, To> {

        To processToClient(From from);
    }

    public interface MultiProcessor<From, To> {
        List<To> processToClient(From source);
    }
}
